package com.ccovo.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ccovo.config.satoken.StpKit;
import com.ccovo.domain.constants.Constants;
import com.ccovo.domain.dto.PageDTO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ccovo.domain.dto.Req.LoginReq;
import com.ccovo.domain.dto.UserDTO.UserEditDTO;
import com.ccovo.domain.po.User;
import com.ccovo.domain.query.UserQuery;
import com.ccovo.domain.vo.UserVO;
import com.ccovo.enums.ErrorCode;
import com.ccovo.exception.BusinessException;
import com.ccovo.mapStructMapper.UserConvertMapper;
import com.ccovo.mapper.UserMapper;
import com.ccovo.service.IUserService;
import com.ccovo.utils.ThrowUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.implementation.bytecode.Throw;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
* @author Maxio
* @description 针对表【user】的数据库操作Service实现
* @createDate 2024-12-20 19:52:42
*/
@Service
@RequiredArgsConstructor
public class IUserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private final UserMapper userMapper;
    private final UserConvertMapper convertMapper;

    /**
     * 新增用户信息
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public Long saveUser(User user) {
        int result = userMapper.insert(user);
        ThrowUtils.throwIf(result <= 0, ErrorCode.OPERATION_ERROR, "新增用户信息失败");
        return user.getId();
    }

    /**
     * 根据id查询用户信息
     * @param id 用户id
     * @return 结果
     */
    @Override
    public User selectById(Long id) {
        ThrowUtils.throwIf(id == null, ErrorCode.PARAMS_ERROR, ErrorCode.PARAMS_ERROR.getMessage());

        User user = userMapper.selectById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR, ErrorCode.NOT_FOUND_ERROR.getMessage());

        return user;
    }

    /**
     * 修改用户信息
     * @param editDTO 用户信息
     * @return 结果
     */
    @Override
    public Boolean updateUserById(UserEditDTO editDTO) {
        User user = BeanUtil.copyProperties(editDTO, User.class);
        int result = userMapper.updateById(user);
        ThrowUtils.throwIf(result <= 0, ErrorCode.OPERATION_ERROR, ErrorCode.OPERATION_ERROR.getMessage());
        return Boolean.TRUE;
    }

    /**
     * 删除用户信息
     * @param id 用户id
     * @return 结果
     */
    @Override
    public Boolean deleteById(Long id) {
        ThrowUtils.throwIf(id == null, ErrorCode.PARAMS_ERROR, ErrorCode.PARAMS_ERROR.getMessage());
        int result = userMapper.deleteById(id);
        ThrowUtils.throwIf(result <= 0, ErrorCode.OPERATION_ERROR, ErrorCode.OPERATION_ERROR.getMessage());
        return Boolean.TRUE;
    }

    /**
     * 分页查询用户信息
     * @param userQuery 查询条件
     * @return 结果
     */
    @Override
    public PageDTO<UserVO> selectPage(UserQuery userQuery) {
        String name = userQuery.getName();
        String role = userQuery.getRole();
        String phone = userQuery.getPhone();
        String email = userQuery.getEmail();

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.isNoneBlank(name), User::getName, name)
                .eq(StringUtils.isNoneBlank(role), User::getRole, role)
                .eq(StringUtils.isNoneBlank(phone), User::getPhone, phone)
                .eq(StringUtils.isNoneBlank(email), User::getEmail, email);

        Page<User> p = new Page<>(userQuery.getPageNo(), userQuery.getPageSize());
        IPage<User> page = userMapper.selectPage(p, wrapper);
        return new PageDTO<>(page.getTotal(), page.getPages(), BeanUtil.copyToList(page.getRecords(), UserVO.class));
    }

    /**
     * 账号密码登录
     * @param loginReq 登录信息
     * @return 结果
     */

    @Override
    public UserVO login(LoginReq loginReq) {
        String username = loginReq.getUsername();
        String password = loginReq.getPassword();

        ThrowUtils.throwIf(username.isEmpty() || password.isEmpty(), ErrorCode.PARAMS_ERROR, ErrorCode.PARAMS_ERROR.getMessage());
        User dbUser = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));

        ThrowUtils.throwIf(dbUser == null, ErrorCode.USER_NOT_EXIST_ERROR, ErrorCode.USER_NOT_EXIST_ERROR.getMessage());
        String pwd = SecureUtil.sha256(password + Constants.SALT);
        if (!dbUser.getPassword().equals(pwd)) {
            throw new BusinessException(ErrorCode.USER_ACCOUNT_ERROR);
        }

//        StpUtil.login(dbUser.getId());
//        StpUtil.getSession().set(Constants.ROLE, dbUser.getRole());
//        UserVO vo = convertMapper.entityToVO(dbUser);
//        vo.setToken(StpUtil.getTokenValue());
        StpKit.USER.login(dbUser.getId());
        StpKit.USER.getSession().set(Constants.ROLE, dbUser.getRole());
        UserVO vo = convertMapper.entityToVO(dbUser);
        vo.setToken(StpKit.USER.getTokenValue());

        System.out.println("当前会话登录Token：" + StpKit.USER.getTokenValue());
        return vo;
    }


}




